package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealDishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealDishService setmealDishService;

    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info("dishDto==>{}", dishDto);

        dishService.saveWithFlavor(dishDto);

        return R.success("新增菜品成功");
    }



    /**
     * 分页查询菜品信息
     * @return
     *
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        // 构造分页构造器对象
        Page<Dish> pageinfo = new Page<>(page, pageSize);
        // DishDto包含属性categoryName
        Page<DishDto> dishDtoPage = new Page<>(page, pageSize);
        // 条件构造器
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 添加过滤条件
        lambdaQueryWrapper.like(name != null, Dish::getName, name);
        // 添加排序条件
        lambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);
        // 执行分页查询，此时pageinfo中已经存放分页数据，但是不包含菜品分类名称
        dishService.page(pageinfo, lambdaQueryWrapper);

        BeanUtils.copyProperties(pageinfo, dishDtoPage, "records");

        List<Dish> records = pageinfo.getRecords();

        List<DishDto> dishDtoRecords = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            // 获取菜品分类id
            Long categoryId = item.getCategoryId();
            // 根据id查询分类名称
            Category category = categoryService.getById(categoryId);
            // 数据判空
            if(category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        // 将加入分类名称的records加入dishDtoPage
        dishDtoPage.setRecords(dishDtoRecords);
        return R.success(dishDtoPage);
    }

    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 菜品修改
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info("dishDto==>{}", dishDto);

        dishService.updateWithFlavor(dishDto);

        return R.success("修改菜品成功");
    }

    /**
     * 根据菜品分类id，查询对应分类下的所有菜品并返回
     * 为套餐添加提供服务
     * @param dish
     * @return
     */
//    @GetMapping("/list")
//    public R<List<Dish>> list(Dish dish) {
//
//        // 构造查询条件
//        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
//        // 生成排序条件
//        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//        // 查询
//        List<Dish> dishes = dishService.list(queryWrapper);
//        return R.success(dishes);
//    }

    /**
     * 根据菜品id，查询对应分类下的所有菜品，添加对应口味并返回
     * @param dish
     * @return
     */

    @GetMapping("/list")
    @Cacheable(value = "dishCache", key = "#dish.categoryId")
    public R<List<DishDto>> list(Dish dish) {

        // 构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        // 生成排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        // 查询， 此时列表中没有DishFlavor
        List<Dish> dishes = dishService.list(queryWrapper);

        List<DishDto> dishDtos = dishes.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);

            LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper();
            qw.eq(DishFlavor::getDishId, item.getId());
            List<DishFlavor> dishFlavors = dishFlavorService.list(qw);
            dishDto.setFlavors(dishFlavors);
            return dishDto;
        }).collect(Collectors.toList());

        return R.success(dishDtos);
    }

    /**
     * 停售菜品 或 停售菜品
     * @param st
     * @param ids
     * @return
     */
    @PostMapping("/status/{st}")
    public R<String> status(@PathVariable("st") Integer st, @RequestParam List<Long> ids) {
        log.info("st={}, ids={}", st, ids);
        // 检查ids是否存在于套餐中
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SetmealDish::getDishId, ids);
        List<SetmealDish> setmealDishes = setmealDishService.list(queryWrapper);
        if(setmealDishes.size() == 0 || st == 1) {
            // 不存在直接停售
            // 根据菜品id获取所有的菜品信息，
            List<Dish> dishes = dishService.listByIds(ids);
            // 修改所有菜品信息的售卖状态
            dishes.stream().map((item) -> {
                item.setStatus(st);
                return item;
            }).collect(Collectors.toList());
            dishService.updateBatchById(dishes);
        } else {
            // 存在时，报错，返回当前套餐中包含该菜品，无法停售；
            throw new CustomException("当前有套餐中包含该菜品，无法停售!!!");
        }
        return R.success("更新菜品状态成功");
    }

    /**
     * 批量删除菜品
     * @param ids
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {
        // 菜品只有停售才能被删除
        log.info("ids=>{}", ids);
        LambdaQueryWrapper<SetmealDish> setmealDishqueryWrapper = new LambdaQueryWrapper<>();
        setmealDishqueryWrapper.in(SetmealDish::getDishId, ids);
        List<SetmealDish> setmealDishes = setmealDishService.list(setmealDishqueryWrapper);
        if (setmealDishes.size() != 0) {
            throw new CustomException("存在未停售套餐包含选中的菜品，无法删除");
        }

        // 套餐中不包含当前菜品才能被删除。
        LambdaQueryWrapper<Dish> dishqueryWrapper = new LambdaQueryWrapper<>();
        dishqueryWrapper.in(Dish::getId, ids);
        dishqueryWrapper.eq(Dish::getStatus, 1);
        List<Dish> dishlist = dishService.list(dishqueryWrapper);

        if(dishlist.size() != 0) {
            throw new CustomException("选中菜品中存在未停售，无法删除");
        }
        dishService.removeByIds(ids);
        return R.success("删除菜品成功");
    }
}
